package zhang.lao.console.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import zhang.lao.build.mybatis.jdbc.auto.model.*;
import zhang.lao.build.tool.FileTool;
import zhang.lao.build.tool.PathKit;
import zhang.lao.dao.base.WnCompanyDao;
import zhang.lao.dao.base.WnFarmDao;
import zhang.lao.dao.base.WnMachineDao;
import zhang.lao.pojo.console.ConsoleContext;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.List;

/**
 * Created by zhangqin on 2017/2/13.
 */
@Component
public class MakeNjQrCodeService {

    @Resource
    private WnMachineDao wnMachineDao;
    @Resource
    private WnFarmDao wnFarmDao;
    @Resource
    private WnCompanyDao wnCompanyDao;
    /**
     * 获取单个二维码图片
     * @param id
     * @param outputStream
     * @return
     * @throws Exception
     */
    public OutputStream getImageByNjId(String id,OutputStream outputStream) throws Exception {

        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);   //设置白边
        WnMachine wnNjxx = wnMachineDao.selectByPrimaryKey(id);
        ImageIO.write(compoundImage(wnNjxx),"JPEG",outputStream);
        return outputStream;
    }

    /**
     * 将二维码生成到指定目录
     * @param consoleContext
     * @throws Exception
     */
    public void makeImage(ConsoleContext consoleContext) throws Exception {
        WnMachineExample wnNjxxExample = new WnMachineExample();
        wnNjxxExample.createCriteria().andFarmIdIn(consoleContext.getFarms());
        List<WnMachine> wnNjxxList = wnMachineDao.selectByExample(wnNjxxExample);
        File file1 =   new File(PathKit.getWebRootPath()+File.separator+"WEB-INF"+File.separator+"file"+File.separator+"njqrcode"+File.separator+consoleContext.getUserId());
        if(file1.exists()){
            FileTool.deleteFile(file1);
        }
        for (WnMachine wnNjxx : wnNjxxList) {

            WnFarm wnJdxx = wnFarmDao.selectByPrimaryKey(wnNjxx.getFarmId());
            File file =  new File(PathKit.getWebRootPath()+File.separator+"WEB-INF"+File.separator+"file"+File.separator+"njqrcode"+File.separator+consoleContext.getUserId()+File.separator+wnJdxx.getName()+File.separator+wnNjxx.getMachineNumber()+".jpg");
            file.mkdirs();
            if(file.exists()){
                FileTool.deleteFile(file);
            }else {
                file.createNewFile();
            }
            ImageIO.write(compoundImage(wnNjxx),"jpg",file);
        }
    }

    /**
     * 合成图片
     * @return
     */
    public BufferedImage compoundImage(WnMachine wnNjxx) throws Exception {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 2);   //设置白边
        JSONObject qr = new JSONObject();
        qr.put("cph", wnNjxx.getLicensePlateNumber());
        qr.put("number", wnNjxx.getMachineNumber());
        WnFarm wnFarm = wnFarmDao.selectByPrimaryKey(wnNjxx.getFarmId());
        qr.put("gsmc",wnCompanyDao.selectByPrimaryKey(wnFarm.getCompanyId()).getName());
        qr.put("ssjd",wnFarm.getName());
        BitMatrix bitMatrix = new MultiFormatWriter().encode("http://api.calbs.cn/qrcode/mechine/"+wnNjxx.getMachineNumber(), BarcodeFormat.QR_CODE, 240, 240, hints);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        BufferedImage image0 = getNjxxImage(qr);
        BufferedImage newImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) newImage.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,400,400);//填充整个屏幕
        g.drawImage(image, 80, 0, null);
        g.drawImage(image0, 0, 240, null);
        return newImage;
    }

    /**
     * 获取农机信息图片
     * @return
     */
    public static BufferedImage getNjxxImage(JSONObject qr){
        //300 240
        int width = 400;
        int height = 160;
        String s1 = "车牌号："+qr.getString("cph");
        String s5 = "编号："+qr.getString("number");
        String s2 = "基地："+qr.getString("ssjd");
        String s3= "公司："+qr.getString("gsmc");
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)bi.getGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
        g2.setFont( new Font("黑体",Font.BOLD,16));
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.black);
        g2.drawString(s1, 100, 16);
        g2.drawString(s5, 100, 36);
        g2.drawString(s2, 100, 56);
        if(s3.length()>10){
            String substring = s3.substring(0, 14);
            String substring2 = s3.substring(14, s3.length());
            g2.drawString(substring, 100, 76);
            g2.drawString(substring2, 150, 96);
        }else{
            g2.drawString(s3, 100, 76);
        }

        g2.setFont( new Font("黑体",Font.BOLD,16));
        g2.drawString("中国农业大学", 150, 136);
        return bi;
    }


    public static void main(String[] args) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 2);   //设置白边
        JSONObject qr = new JSONObject();
        qr.put("cph", "实打实地方");
        qr.put("number", "实打实地方");
        qr.put("gsmc", "实打实是的发送到发送到第三方地方");
        qr.put("ssjd", "实打实地方");
        BitMatrix bitMatrix = new MultiFormatWriter().encode("http://api.calbs.cn/qrcode/mechine/", BarcodeFormat.QR_CODE, 240, 240, hints);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        BufferedImage image0 = getNjxxImage(qr);
        BufferedImage newImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) newImage.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,400,400);//填充整个屏幕
        g.drawImage(image, 80, 0, null);
        g.drawImage(image0, 0, 240, null);

        ImageIO.write(newImage,"jpg",new File("e:/3.jpg"));
    }
}
